package com.hjsmallfly.syllabus.ext

import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.SimpleItemAnimator
import android.view.LayoutInflater
import android.view.ViewGroup

fun RecyclerView.disableRefreshAnimator() {
    (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
}

fun RecyclerView.disableAllAnimator() {
    itemAnimator = null
}


fun RecyclerView.parseView(layoutId: Int) = LayoutInflater.from(context)
        .inflate(
                layoutId, parent as ViewGroup, false
        )

val RecyclerView.isTopWhenIfNotEmpty: Boolean
    get() {
        //得到当前界面可见数据的大小
        val visibleItemCount = layoutManager?.childCount ?: 0
        //得到当前界面，第一个子视图的position
        val firstVisibleItemPosition = (layoutManager as LinearLayoutManager)
                .findFirstCompletelyVisibleItemPosition()
        if (visibleItemCount != 0 && firstVisibleItemPosition == 0) {
            return true
        }
        return false
    }


fun RecyclerView.setOnScrollToTopListener(listener: () -> Unit) {
    addOnScrollListener(object : RecyclerView.OnScrollListener() {


        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            //得到当前界面可见数据的大小
            val visibleItemCount = layoutManager?.childCount?:0

            //得到当前界面，第一个子视图的position
            val firstVisibleItemPosition = (layoutManager as LinearLayoutManager)
                    .findFirstCompletelyVisibleItemPosition()
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                if (visibleItemCount != 0 && firstVisibleItemPosition == 0) {
                    listener.invoke()
                }
            }
        }
    })
}